package com.example.boot.quartz.task;

import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.ResourceUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.FileNotFoundException;

/**
 * 定时任务工作
 *
 * @author ding
 * @since 2024/7/15
 */
@Slf4j
public class MyQuartz extends QuartzJobBean {

    @Autowired
    private JavaMailSender javaMailSender;

    String from = "207409830@qq.com";
    String to = "3168850469@qq.com";
    String subject = "丁昊旻的作业  为项目之间传递json字符串";

    //晚上十点发送邮件
    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("开始执行任务！！");
        String content = "redis在项目中的实现";
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;   //multipart设置为true代表允许支持携带附件
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        try {
            mimeMessageHelper.setFrom(from+"(丁昊旻)");
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content);

            //携带附件
            File file1 = ResourceUtils.getFile("classpath:redis1.png");
            File file2 = ResourceUtils.getFile("classpath:redis2.png");
            mimeMessageHelper.addAttachment("redis1.png", file1);
            mimeMessageHelper.addAttachment("redis2.png", file2);
            javaMailSender.send(mimeMessage);;
            log.info("邮件发送完毕！！！");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
